// 支付路由
const express = require('express');
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const { query, transaction } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');
const { validateRecharge } = require('../middleware/validation');
const { generateRandomString, formatAmount } = require('../utils/helpers');
const ResponseHelper = require('../utils/response');

// 生成支付二维码
router.post('/qrcode', authenticateToken, async (req, res) => {
  try {
    const { orderId, amount } = req.body;
    const userId = req.user.id;

    if (!orderId || !amount || amount <= 0) {
      return ResponseHelper.error(res, '订单ID和支付金额必须提供且大于0', 400);
    }

    // 检查订单是否存在
    const orders = await query('SELECT * FROM orders WHERE id = ?', [orderId]);
    if (orders.length === 0) {
      return ResponseHelper.notFound(res, '订单不存在');
    }

    const order = orders[0];

    // 检查订单是否属于当前用户
    if (order.user_id !== userId) {
      return ResponseHelper.error(res, '无权限操作此订单', 403);
    }

    // 检查订单状态
    if (order.status !== 'pending') {
      return ResponseHelper.error(res, '订单状态不允许支付', 400);
    }

    // 检查金额是否匹配
    if (parseFloat(amount) !== parseFloat(order.total_cost)) {
      return ResponseHelper.error(res, '支付金额与订单金额不匹配', 400);
    }

    // 生成支付订单号
    const paymentId = `PAY${Date.now()}${generateRandomString(6)}`;

    // 模拟二维码数据（实际项目中应该调用支付平台API）
    const qrCodeData = {
      payment_id: paymentId,
      order_id: orderId,
      amount: formatAmount(amount),
      user_id: userId,
      expires_at: new Date(Date.now() + 15 * 60 * 1000), // 15分钟过期
      qr_code: `yiganyunshu://payment/${paymentId}/${orderId}/${amount}` // 模拟二维码URL
    };

    ResponseHelper.success(res, qrCodeData, '支付二维码生成成功');

  } catch (error) {
    console.error('生成支付二维码错误:', error);
    ResponseHelper.serverError(res, '生成支付二维码失败');
  }
});

// 验证二维码
router.post('/validate-qr', async (req, res) => {
  try {
    const { qr_code } = req.body;

    if (!qr_code) {
      return ResponseHelper.error(res, '二维码数据不能为空', 400);
    }

    // 模拟二维码验证逻辑
    // 实际项目中应该从数据库或缓存中查询支付订单信息
    const isValid = qr_code.includes('yiganyunshu.com');
    
    if (!isValid) {
      return ResponseHelper.error(res, '无效的二维码', 400);
    }

    // 提取支付ID
    const paymentId = qr_code.split('/').pop();

    ResponseHelper.success(res, {
      valid: true,
      payment_id: paymentId,
      message: '二维码验证成功'
    }, '二维码验证成功');

  } catch (error) {
    console.error('验证二维码错误:', error);
    ResponseHelper.serverError(res, '验证二维码失败');
  }
});

// 处理支付
router.post('/pay', authenticateToken, async (req, res) => {
  try {
    const { orderId, amount, qrData } = req.body;
    const userId = req.user.id;

    if (!orderId || !amount) {
      return ResponseHelper.error(res, '订单ID和金额不能为空', 400);
    }

    // 检查订单是否存在
    const orders = await query('SELECT * FROM orders WHERE id = ?', [orderId]);
    if (orders.length === 0) {
      return ResponseHelper.notFound(res, '订单不存在');
    }

    const order = orders[0];

    // 检查订单是否属于当前用户
    if (order.user_id !== userId) {
      return ResponseHelper.error(res, '无权限操作此订单', 403);
    }

    // 检查订单状态
    if (order.status !== 'pending') {
      return ResponseHelper.error(res, '订单状态不允许支付', 400);
    }

    // 检查金额是否匹配
    if (parseFloat(amount) !== parseFloat(order.total_cost)) {
      return ResponseHelper.error(res, '支付金额与订单金额不匹配', 400);
    }

    // 检查用户余额
    const users = await query('SELECT balance FROM users WHERE id = ?', [userId]);
    const userBalance = parseFloat(users[0].balance);

    if (userBalance < parseFloat(amount)) {
      return ResponseHelper.error(res, '余额不足，请先充值', 400);
    }

    await transaction(async (connection) => {
      // 扣除用户余额
      await connection.execute(
        'UPDATE users SET balance = balance - ?, updated_at = NOW() WHERE id = ?',
        [amount, userId]
      );

      // 更新订单状态为已支付
      await connection.execute(
        'UPDATE orders SET status = "confirmed", updated_at = NOW() WHERE id = ?',
        [orderId]
      );

      // 如果是当前时间段，更新台球桌状态
      const now = new Date();
      const bookingStart = new Date(`${order.booking_date} ${order.start_time}`);
      const bookingEnd = new Date(`${order.booking_date} ${order.end_time}`);

      if (now >= bookingStart && now <= bookingEnd) {
        await connection.execute(
          'UPDATE tables SET status = "occupied", updated_at = NOW() WHERE id = ?',
          [order.table_id]
        );
      }
    });

    // 获取更新后的用户余额
    const updatedUsers = await query('SELECT balance FROM users WHERE id = ?', [userId]);
    const remainingBalance = parseFloat(updatedUsers[0].balance);

    const paymentResult = {
      orderId,
      amount: parseFloat(amount),
      remainingBalance,
      status: 'success',
      transaction_id: `TXN${Date.now()}${generateRandomString(8)}`,
      paid_at: new Date().toISOString()
    };

    ResponseHelper.success(res, paymentResult, '支付成功');

  } catch (error) {
    console.error('处理支付错误:', error);
    ResponseHelper.serverError(res, '支付处理失败');
  }
});

// 支付回调（模拟）
router.post('/callback', async (req, res) => {
  try {
    const { payment_id, status, amount, user_id, type, order_id } = req.body;

    if (status === 'success') {
      await transaction(async (connection) => {
        if (type === 'recharge') {
          // 充值成功：更新用户余额
          await connection.execute(
            'UPDATE users SET balance = balance + ?, updated_at = NOW() WHERE id = ?',
            [amount, user_id]
          );

          // 记录充值记录
          await connection.execute(
            `INSERT INTO recharge_records (user_id, amount, payment_method, status, remark, created_at) 
             VALUES (?, ?, 'virtual', 'completed', '虚拟支付', NOW())`,
            [user_id, amount]
          );
        } else if (type === 'order' && order_id) {
          // 订单支付成功：更新订单状态
          await connection.execute(
            'UPDATE orders SET status = "confirmed", updated_at = NOW() WHERE id = ?',
            [order_id]
          );
        }
      });
    }

    ResponseHelper.success(res, { received: true }, '支付回调处理成功');

  } catch (error) {
    console.error('支付回调处理错误:', error);
    ResponseHelper.serverError(res, '支付回调处理失败');
  }
});

// 获取支付状态
router.get('/status/:payment_id', authenticateToken, async (req, res) => {
  try {
    const { payment_id } = req.params;

    // 模拟查询支付状态
    // 实际项目中应该从数据库或支付平台查询真实状态
    const paymentStatus = {
      payment_id,
      status: 'pending', // pending, success, failed, expired
      amount: '0.00',
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    };

    ResponseHelper.success(res, paymentStatus, '获取支付状态成功');

  } catch (error) {
    console.error('获取支付状态错误:', error);
    ResponseHelper.serverError(res, '获取支付状态失败');
  }
});

module.exports = router;
